package com.adminsystem.java.excelFile.controller;

import com.adminsystem.java.common.PageResult;
import com.adminsystem.java.common.Result;
import com.adminsystem.java.excelFile.pojo.param.StudentScorePageParam;
import com.adminsystem.java.excelFile.pojo.vo.StudentScoreVO;
import com.adminsystem.java.excelFile.service.StudentScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.excel.EasyExcel;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author wangpeiao
 */
@RestController
@RequestMapping("/myAdminSystem/studentScore")
public class StudentScoreController {
    @Autowired
    private StudentScoreService studentScoreService;

    /**
     * 分页查询学生成绩
     */
    @GetMapping("/list")
    public PageResult<StudentScoreVO> list(StudentScorePageParam param) {
        return studentScoreService.queryByPage(param);
    }

    /**
     * 导出学生成绩数据到Excel
     */
    @GetMapping("/export")
    public void export(StudentScorePageParam param, HttpServletResponse response) throws Exception {
        // 设置响应头信息
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("学生成绩表", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 查询所有数据
        List<StudentScoreVO> scoreVOList = studentScoreService.exportAll(param);

        // 转换为Excel模型
        List<StudentScoreVO> excelVOList = scoreVOList.stream()
                .map(vo -> {
                    StudentScoreVO excelVO = new StudentScoreVO();
                    BeanUtils.copyProperties(vo, excelVO);
                    return excelVO;
                })
                .collect(Collectors.toList());

        // 写入Excel并响应给前端
        EasyExcel.write(response.getOutputStream(), StudentScoreVO.class)
                .sheet("学生成绩")
                .doWrite(excelVOList);
    }

    /*
    * 下载模版
    * */
    @PostMapping("/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        List<StudentScoreVO> templateData = new ArrayList<>();

        // 可选：添加示例数据行
        StudentScoreVO example = new StudentScoreVO();
        example.setName("张三");
        example.setAge(18);
        example.setGender("男");
        example.setClassName("高三(1)班");
        example.setStudentNumber("20210001");
        example.setChinese(85);
        example.setMath(90);
        example.setEnglish(88);
        example.setPhysics(92);
        example.setBiology(87);
        example.setChemistry(89);
        example.setPolitics(93);
        example.setHistory(91);
        example.setGeography(90);
        example.setAttendance("全勤");
        example.setPerformance("优秀");

        templateData.add(example);

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("学生成绩导入模板", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 使用 EasyExcel 写出模板
        EasyExcel.write(response.getOutputStream(), StudentScoreVO.class)
                .sheet("学生成绩")
                .doWrite(templateData);
    }

    /**
     * 导入excel数据
     */
    @PostMapping("/import")
    public Result<String> importExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("上传的文件为空");
        }
        try {
            return studentScoreService.importExcel(file);
        } catch (Exception e) {
            return Result.fail("导入失败：" + e.getMessage());
        }
    }


}
